package com.ztf666.service.impl;


import com.ztf666.service.IndexService;
import com.ztf666.utils.ConnectionUtils;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;

import java.io.IOException;

/**
 * @Author ztf
 * @Date 20:38 2022/1/17
 **/
public class IndexServiceImpl implements IndexService {

    @Override
    public void createIndex(String index) throws IOException {
        RestHighLevelClient restHighLevelClient = ConnectionUtils.getClient();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        createIndexRequest.settings(Settings.builder()
                //设置分片数
                .put("number_of_shards",5)
                //备份数据
                .put("number_of_replicas",1)
                .build()
        );
        XContentBuilder xContentBuilder = JsonXContent.contentBuilder().startObject()
                .startObject("properties")
                .startObject("name").field("type", "text").field("analyzer", "ik_max_word")
                .endObject().startObject("count").field("type", "long").endObject()
                .startObject("on-sale").field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis").endObject()
                .startObject("descr").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .endObject().endObject();
        //设置列信息
        createIndexRequest.mapping(xContentBuilder);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.err.println(createIndexResponse);
    }

    @Override
    public void createIndex(CreateIndexRequest request) throws IOException {
        RestHighLevelClient highLevelClient = ConnectionUtils.getClient();
        CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.err.println(createIndexResponse);
    }
}
